import React, { useEffect, useState } from 'react';
import '../../styles/Customcenter.scss'
import { Divider, Radio } from 'antd';

import { Table, Button, TablePaginationConfig, notification, Upload, Modal, Form, } from 'antd'
import { Input } from 'antd';

import type { ColumnsType } from 'antd/es/table'
import { custom_search, custom_del, custom_delmany, custom_changeleader } from '../../utils/api'
import { read } from 'fs';

const { Search } = Input;

interface Props {
}

//定义每一行的数据对象类型
interface DataType {
    name: string;
    phone: string;
    email: string;
    address: string;
    leader: string;
    time: string;
    key: string;
}

function Customcenter(props: Props) {
    // 获取客户列表
    var [cutomlist, setCutomlist] = useState([])

    //决定了每一列渲染什么数据
    const columns: ColumnsType<DataType> = [
        {
            title: '姓名', //表格列的名字(显示在表格头上)
            dataIndex: 'name', //数据对应的属性名
            //key: 'name' //key是必须的,每一列不同.
            // render: (text: string) => <a>{text}</a>,
        },
        {
            title: '手机号',
            dataIndex: 'phone',
        },
        {
            title: '邮箱',
            dataIndex: 'email',
        },
        {
            title: '地址',
            dataIndex: 'address'
        },

        {
            title: '负责人',
            dataIndex: 'leader',
            key: 'leader'
        },
        {
            title: '呼入时间',
            dataIndex: 'time',
            key: 'time'
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <>
                    <button onClick={() => { delt(record) }} className='iconfont icon-delete'>删除</button>
                </>
            ),
        },
    ];

    //决定了每一行渲染什么数据
    const data: DataType[] = cutomlist

    // 获取数据
    useEffect(() => {
        custom_search().then((res) => {
            setCutomlist(res.data.list)
            setPagination({ current: 1, pageSize: 10, total: res.data.total })//保存总数
        })
    }, [])

    //分页器
    var [pagination, setPagination] = useState<TablePaginationConfig>({ current: 1, pageSize: 10, total: 0 })
    var [loading, setLoading] = useState(false);

    //分页
    const handleChange = (pagination: TablePaginationConfig) => {
        // // 发请求，获取最新页码对应的数据
        setPagination(pagination)//更新页码
        setLoading(true)
        //pagination 参数 包含有当前最新页码
        //在这里发请求, 获取最新页码对应的数据
        custom_search({ searchKey: '', page: pagination.current, count: pagination.pageSize }).then((res) => {
            setLoading(false);
            setCutomlist(res.data.list)
        });

    }

    //搜索
    const onSearch = (value: string) => {
        //搜索
        console.log(value);
        console.log({ searchKey: value, page: pagination.current, count: pagination.pageSize });

        custom_search({ searchKey: value, page: pagination.current, count: pagination.pageSize }).then((res) => {
            setCutomlist(res.data.list)
            console.log(res.data.list);

        });
    };

    // 点击删除，删除行
    const delt = (item: any) => {
        var it = {
            id: item._id,
            searchKey: '',
            page: pagination.current,
            count: pagination.pageSize
        }
        custom_del(it).then((res) => {
            if (res.data.code == 200) {
                notification.success({ message: '删除成功！' });
                custom_search({ searchKey: '', page: pagination.current, count: pagination.pageSize }).then((res) => {
                    setCutomlist(res.data.list)
                });
            }
        })
    }

    // 删除选中的所有行
    const deleteAll = () => {
        custom_delmany({ keys: selectedRowKeys, searchKey: '', page: pagination.current, count: pagination.pageSize }).then((res) => {
            notification.success({ message: '删除成功！' });
            custom_search({ searchKey: '', page: pagination.current, count: pagination.pageSize }).then((res) => {
                setCutomlist(res.data.list)
            });
        })
    }

    // 复选框
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    // 选择发生改变的回调
    const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
        // console.log('selectedRowKeys changed: ', newSelectedRowKeys);
        setSelectedRowKeys(newSelectedRowKeys);
    };

    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };

    // 上传状态发生改变回调
    var handleUploadChange = (res: any) => {
        if (res.file.status == 'done' && res.file.response.code == 200) { //上传成功
            notification.success({ message: '上传成功!' });
        }
    }

    // 修改负责人
    // 控制修改表单的显示或隐藏
    const [isModalOpen, setIsModalOpen] = useState(false);
    // 角色列表
    var [options, setOptions] = useState([])
    // 修改表单显示
    const showModal = () => {
        setIsModalOpen(true);
    };
    const handleOk = () => {
        setIsModalOpen(false);
    };

    const handleCancel = () => {
        setIsModalOpen(false);
    };

    // 修改表单验证通过，执行
    const onFinish = (values: any) => {
        console.log(values.leader);

        custom_changeleader({ leader: values.leader, keys: selectedRowKeys, searchKey: '', page: pagination.current, count: pagination.pageSize }).then((res) => {
            if (res.data.code == 200) {
                notification.success({ message: '修改成功！' });
                custom_search({ searchKey: '', page: pagination.current, count: pagination.pageSize }).then((res) => {
                    setCutomlist(res.data.list)
                    setIsModalOpen(false);
                });
            }

        })
    }

    return (
        <div>
            <div className='customcenter'>
                <p>客户管理</p>
                <div className="opet">
                    <Search style={{ width: 300, marginRight: 20 }} placeholder="输入员工姓名" onSearch={onSearch} enterButton />
                </div>
                <div className="opet2">
                    <div className="left">
                        <Button disabled={selectedRowKeys.length == 0}>创建人工外呼</Button>
                        <Button disabled={selectedRowKeys.length == 0}>写入机器外呼</Button>
                        <Button disabled={selectedRowKeys.length == 0}>发送消息</Button>
                        <Button disabled={selectedRowKeys.length == 0} onClick={showModal}>设定负责人</Button>
                        <Modal title="设定负责人" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
                            <Form
                                name="basic"
                                labelCol={{ span: 6 }}
                                wrapperCol={{ span: 18 }}
                                onFinish={onFinish}
                            >
                                <Form.Item
                                    label="负责人"
                                    name="leader"
                                    rules={[{ required: true, message: '输入负责人' }]}
                                >
                                    <Input placeholder='输入负责人' />
                                </Form.Item>
                                <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                                    <Button type="primary" htmlType="submit">
                                        修改
                                    </Button>
                                </Form.Item>
                            </Form>
                        </Modal>
                        <Button disabled={selectedRowKeys.length == 0} onClick={deleteAll}>删除</Button>
                    </div>
                    <div className="right">
                        <Upload accept='.xls,.xlsx' action='/api/custom/import' name="excel" onChange={handleUploadChange} showUploadList={false}>
                            <Button type='primary'>导入客户</Button>
                        </Upload>
                        <Button type='primary' href='/api/custom/export'>导出客户</Button>
                    </div>
                </div>
                {/* 表格组件 */}
                {/* columns 表格每一列如何渲染 */}
                {/* dataSource 表格的数据源 */}

                <Divider />
                <Table
                    rowSelection={rowSelection}
                    columns={columns}
                    dataSource={data}
                    pagination={pagination}
                    onChange={handleChange}
                    size={'middle'}
                />

            </div>
        </div >
    );
}

export default Customcenter;
